//
//  WYWSessionService.m
//  15WClient
//
//  Created by JinYong on 16/4/24.
//  Copyright © 2016年 15w. All rights reserved.
//

#import "WYWSessionService.h"
#import "WYWHTTPSessionManager.h"
//#import "Reachability.h"
#import "WYWNetworkSerialization.h"

#import <CommonCrypto/CommonDigest.h>
#import <CoreTelephony/CTCarrier.h>
#import <CoreTelephony/CTTelephonyNetworkInfo.h>

#import "WYWDeviceUtil.h"


//检测网络 YES为无网或未知网络状态
#define AFNetworkNotReachability ([AFNetworkReachabilityManager sharedManager].networkReachabilityStatus <= 0)
#define kDefaultSuccessCode     (10000)

#define kCacheDataExpireTime    (60 * 60 * 24)

@implementation WYWSessionService
+ (NSURLSessionDataTask *)startGetRequest:(NSString *)url
                                  path:(NSString *)path
                                params:(NSDictionary *)params
                               success:(WYWRequestSuccessBlock)success
                                  failure:(WYWRequestFailBlock)failure {
    NSURLSessionDataTask *task =
    [WYWSessionService startRequest:url
                               path:path
                             params:params
                      requestMehtod:WYWNetworkRequestMethodGET
                           encoding:WYWNetworkEncodingNone
                            success:success
                            failure:failure];
    return task;
}

+ (NSURLSessionDataTask *)startPostRequest:(NSString *)url
                                      path:(NSString *)path
                                    params:(NSDictionary *)params
                                   success:(WYWRequestSuccessBlock)success
                                   failure:(WYWRequestFailBlock)failure
{
    NSURLSessionDataTask *task = [WYWSessionService startRequest:url
                               path:path
                             params:params
                      requestMehtod:WYWNetworkRequestMethodPOST
                           encoding:WYWNetworkEncodingNone
                            success:success
                            failure:failure];
    return task;
}


+ (NSURLSessionDataTask *)startRequest:(NSString *)url
                                      path:(NSString *)path
                                    params:(NSDictionary *)params
                             requestMehtod:(WYWNetworkRequestMethod)method
                                  encoding:(WYWNetworkContentEncoding)encoding
                                   success:(WYWRequestSuccessBlock)success
                                   failure:(WYWRequestFailBlock)failure
{
    //判断服务器地址
    NSString *serverUrl = url;
    if (!serverUrl || !serverUrl.length) {
        serverUrl = BaseURL;
    }
    //判断接口地址
    if (!path || !path.length) {
        return nil;
    }
    // target url
    NSMutableString *targetUrl = [[NSMutableString alloc] init];
    [targetUrl appendFormat:@"%@%@",serverUrl,path];
    
    // 设置sessionManager
    WYWHTTPSessionManager *sessionManager = [WYWHTTPSessionManager manager];
    [sessionManager configureHeaderField:WYWRequestHeaderTypeJSON];

    
    NSURLSessionDataTask *dataTask = nil;
    
    switch (method) {
        case WYWNetworkRequestMethodGET:
        {
            dataTask = [sessionManager GET:targetUrl parameters:params progress:^(NSProgress * _Nonnull downloadProgress) {
            } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                if ([responseObject[@"code"] integerValue] == 0) {
                    
                    success(task, responseObject);
                }
                else {
                    NSError *error = [[NSError alloc]
                                      initWithDomain:@""
                                      code:[responseObject[@"code"] integerValue] userInfo:@{kErrorMsgKey:responseObject[@"message"]?:kErrorNoNetworkMsg}];
                    failure(error);
                }
            } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                NSError *error1 = [[NSError alloc]
                                   initWithDomain:@""
                                   code:kErrorNoNetworkCode
                                   userInfo:@{kErrorMsgKey:kErrorNoNetworkMsg}];
                failure(error1);
            }];
        }
            break;
        case WYWNetworkRequestMethodPOST:
        {
            dataTask = [sessionManager POST:targetUrl
                      parameters:params
                        progress:^(NSProgress * _Nonnull uploadProgress) {
                            
                        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                            
                            if ([responseObject[@"code"] integerValue] == kDefaultSuccessCode) {
                                
                                success(task, responseObject);
                            }
                            else {
                                NSError *error = [[NSError alloc]
                                                  initWithDomain:@""
                                                  code:[responseObject[@"code"] integerValue] userInfo:@{kErrorMsgKey:responseObject[@"message"]?:kErrorNoNetworkMsg}];
                                failure(error);
                            }
                        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                            
                            NSError *error1 = [[NSError alloc]
                                               initWithDomain:@""
                                               code:kErrorNoNetworkCode
                                               userInfo:@{kErrorMsgKey:kErrorNoNetworkMsg}];
                            failure(error1);
                        }];
        }
            break;
        default:
            
            break;
    }
    
    return dataTask;
}


#pragma mark - Network Help
// 检测网络
+ (AFNetworkReachabilityStatus)checkNetwork
{
    __block AFNetworkReachabilityStatus statusInNet = AFNetworkReachabilityStatusUnknown;
    
    dispatch_group_t group = dispatch_group_create();
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_group_async(group, queue, ^{
        /**
         AFNetworkReachabilityStatusUnknown          = -1,  // 未知
         AFNetworkReachabilityStatusNotReachable     = 0,   // 无连接
         AFNetworkReachabilityStatusReachableViaWWAN = 1,   // 3G 花钱
         AFNetworkReachabilityStatusReachableViaWiFi = 2,   // 局域网络,不花钱
         */
        dispatch_semaphore_t sema = dispatch_semaphore_create(0);
        [[AFNetworkReachabilityManager sharedManager] startMonitoring];
        [[AFNetworkReachabilityManager sharedManager] setReachabilityStatusChangeBlock:^(AFNetworkReachabilityStatus status) {
            statusInNet = status;
            dispatch_semaphore_signal(sema);
        }];
        dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
    });
    return statusInNet;
}

+ (NSURLSessionDataTask *)startSpecialRequest:(NSString *)url
                                         path:(NSString *)path
                                       params:(NSDictionary *)params
                                requestMehtod:(WYWNetworkRequestMethod)method
                                     encoding:(WYWNetworkContentEncoding)encoding success:(WYWRequestSuccessBlock)success
                                      failure:(WYWRequestFailBlock)failure
                                    checkData:(BOOL)needCheck
                                   User_Agent:(NSString *)user_agent
                                       Cookie:(NSString *)cookie
                                     httpType:(WYWRequestHeaderType)httpType
{
    //判断服务器地址
    NSString *serverUrl = url;
    if (!serverUrl || !serverUrl.length) {
        //        serverUrl = JN_NEW_HTTPS_BASE_URL;
    }
    //判断接口地址
    //    if (!path || !path.length) {
    //        return nil;
    //    }
    NSMutableString *targetUrl = [[NSMutableString alloc] init];
    if ([[serverUrl substringFromIndex:serverUrl.length - 1] isEqualToString:@"/"]) {
        // 以"/"结尾
        [targetUrl appendFormat:@"%@%@",serverUrl,path];
    }else{
        if (path.length > 0) {
            [targetUrl appendFormat:@"%@/%@",serverUrl,path];
        }
        else {
            [targetUrl appendFormat:@"%@",serverUrl];
        }
    }
    
    // 设置sessionManager
    AFHTTPSessionManager *sessionManager;
    
    if (httpType == WYWRequestHeaderTypeSpecial2) {
        sessionManager = [[AFHTTPSessionManager alloc] init];
        sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        sessionManager.responseSerializer = [AFHTTPResponseSerializer serializer];
        sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/javascript",@"application/javascript",@"application/x-javascript",@"application/json", nil];
    }
    else {
        sessionManager = [[AFHTTPSessionManager alloc] init];
        
        sessionManager.requestSerializer = [AFHTTPRequestSerializer serializer];
        sessionManager.responseSerializer = [AFJSONResponseSerializer serializer];
        sessionManager.responseSerializer.acceptableContentTypes = [NSSet setWithObjects:@"text/html",@"text/plain",@"application/json", nil];
    }
    
    NSDictionary *finalParams = [NSDictionary dictionaryWithDictionary:params];
    NSURLSessionDataTask *dataTask = nil;
    switch (method) {
        case WYWNetworkRequestMethodGET:
        {
            dataTask =
            [sessionManager GET:targetUrl
                     parameters:finalParams
                       progress:^(NSProgress * _Nonnull downloadProgress) {
                           
                       }
                        success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                            
                            if(httpType == WYWRequestHeaderTypeSpecial2) {
                                NSString *result = @"";
                                if([responseObject isKindOfClass:[NSDictionary class]]) {
                                    result = [WYWDeviceUtil data2jsonString:responseObject];
                                }
                                else {
                                    result = [[NSString alloc] initWithData:responseObject  encoding:NSUTF8StringEncoding];
                                }
                                success(task, result);
                                return ;
                            }
                            else {
                                NSMutableDictionary *finalData = [NSMutableDictionary dictionaryWithDictionary:responseObject];
                                
                                if ([finalData[@"code"] integerValue] == kDefaultSuccessCode) {
                                    success(task, finalData);
                                }
                                else {
                                    NSError *error = [[NSError alloc]
                                                      initWithDomain:@""
                                                      code:[finalData[@"code"] integerValue]
                                                      userInfo:@{kErrorMsgKey:finalData[@"message"]?:kErrorNoNetworkMsg,
                                                                 kErrorDataKey:finalData[@"data"]?:@{}}];
                                    failure(error);
                                }
                            }
                            
                        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                            
                            NSError *error1 = [[NSError alloc]
                                               initWithDomain:@""
                                               code:kErrorNoNetworkCode userInfo:@{kErrorMsgKey:kErrorNoNetworkMsg}];
                            failure(error1);
                            
                        }];
        }
            break;
        case WYWNetworkRequestMethodPOST:
        {
            dataTask =
            [sessionManager POST:targetUrl
                      parameters:finalParams
                        progress:^(NSProgress * _Nonnull uploadProgress) {
                            
                        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
                            
                            NSMutableDictionary *finalData = [NSMutableDictionary dictionaryWithDictionary:responseObject];
                            
                            if (needCheck) {
                                if ([finalData[@"code"] integerValue] == kDefaultSuccessCode) {
                                    success(task, finalData);
                                }
                                else {
                                    NSError *error = [[NSError alloc]
                                                      initWithDomain:@""
                                                      code:[finalData[@"code"] integerValue]
                                                      userInfo:@{kErrorMsgKey:finalData[@"message"]?:kErrorNoNetworkMsg,
                                                                 kErrorDataKey:finalData[@"data"]?:@{}
                                                                 }];
                                    failure(error);
                                }
                            }
                            else {
                                success(task, finalData);
                            }
                        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
                            NSError *error1 = [[NSError alloc]
                                               initWithDomain:@""
                                               code:kErrorNoNetworkCode
                                               userInfo:@{kErrorMsgKey:kErrorNoNetworkMsg}];
                            failure(error1);
                        }];
        }
            break;
        case WYWNetworkRequestMethodDELETE:
            // 暂无
            break;
        case WYWNetworkRequestMethodPUT:
            // 暂无
            break;
    }
    
    return dataTask;
    
    
}

@end
